<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Permission;

class PermissionController extends Controller
{


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Permission $permission)
    {
        $permissions = $permission->with('parent')->filter($request->all())->orderBy('id','desc')->get();
        $name = $request->name;
        $title = $request->title;
        $permissions = list_to_tree(optional($permissions)->toArray(), 'id', 'parent_id', 'children', 0);
        return view('admins.permission.index',compact('permissions','name', 'title'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    	$parent = (new Permission)->orderBy('id','desc')->get();
    	$parents = list_to_tree(optional($parent)->toArray(), 'id', 'parent_id', 'children', 0);
        return view('admins.permission.add',compact('parents'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Permission $permission)
    {
        $result = $permission::create($request->all());
        if(!$result){
            return back()->with('warning','添加失败');
        }
        return redirect()->route('admin.permissions.index')->with('success', '添加成功');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Permission $permission)
    {
    	$parent = (new Permission)->where('id','<>', $permission->id)->orderBy('id','desc')->get();
    	$parents = list_to_tree(optional($parent)->toArray(), 'id', 'parent_id', 'children', 0);
        return view('admins.permission.edit', compact('permission', 'parents'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Permission $permission)
    {
        $result = $permission->update($request->all());
        if(!$result){
            return back()->with('warning','编辑失败');
        }
        return redirect()->route('admin.permissions.index')->with('success', '编辑成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Permission $permission)
    {
        dd($permission);
    }
}
